<?php 
namespace Emos\Field;

use Emos\Common;

class MultiChoice extends Choice {
    protected $items = array();
    protected $layout;
    
    protected $glue = ',';    


    public function __construct($items, $layout='checkboxes') {
        parent::__construct($items, $layout);
    }

    public function validate() {                    
    }    
        
    public function update() {
        $newValue = $this->getPost(); 
        if($newValue === null) {
            return array($this->dbName => "");        
        }
        else {            
            $newValue = array_intersect($newValue, array_keys($this->items));            
            $v = implode($this->glue, $newValue);                        
            return array($this->dbName => $v);        
        }
    }    
    
    public function html() {
        $html = '';
        
        $valueItems = explode($this->glue, $this->value);
        
        if($this->layout == 'checkboxes' || $this->layout == 'checkboxes_horizontal') {
            foreach($this->items as $value => $label) {
                $s = in_array($value, $valueItems) ? ' checked' : '';
                $html .= "<input name='{$this->htmlName}[]' type='checkbox' value='".Common::plain($value)."'{$s}>".Common::plain($label);
                $html .= ($this->layout == 'checkboxes_horizontal') ? ' &nbsp; ' : '<br>';                
            }          
        }
        else {
            $html .= "<select name='{$this->htmlName}[]' multiple>";
            foreach($this->items as $value => $label) {
                $s = ($value === $this->value) ? ' selected' : '';
                $html .= "<option value='".Common::plain($value)."'{$s}>".Common::plain($label)."</option>";
            }
            $html .= "</select> [CTRL]";              
        }
        
        return $html;
    }
}